﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TiTi.tea.DAL;
using TiTi.tea.Dto;
using TiTi.tea.Model;

namespace TiTi.tea.BLL
{
    public class LoginInfoBLL
    {
        private LoginInfoDAL udal = new LoginInfoDAL();

        public LoginInfo GetByLoginName(string loginName)
        {
            return udal.GetOne(o=>o.LoginName == loginName);
        }

        public UserInfo GetUserinfo(int userId)
        {
            UserInfoDAL userDal = new UserInfoDAL();
            return userDal.GetOne(o => o.Id == userId);
        }

        public IEnumerable<LoginDto> Query(string LoginName, out int Total, int PageSize = 10, int PageIndex = 1)
        {
            var users = new UserInfoDAL().GetAll();
            var data = udal.GetAll();
            Total = data.Count();
            if (!string.IsNullOrEmpty(LoginName))
            {
                data = data.Where(o => o.LoginName.Contains(LoginName));
            }
            return data.OrderBy(o => o.CreateTime).Skip(PageSize * (PageIndex - 1)).Take(PageSize).Select(o=>new LoginDto()
            {
                Id = o.Id,
                UserId=o.Id,
                UserName=users.Where(u=>u.Id==o.UserId).FirstOrDefault().UserName,
                LoginName=o.LoginName,
                LoginPwd=o.LoginPwd,
                LoginCount=o.LoginCount,
                LoginLastTime=o.LoginLastTime,
                CreateTime=o.CreateTime,
                Status=o.Status,
                IsDelete=o.IsDelete,
            });
        }

        public LoginInfo Get(int id)
        {
            return udal.GetOne(o => o.Id == id);
        }

        public bool Update(LoginInfo entity)
        {
            return udal.Update(entity);
        }

        public bool Add(LoginInfo entity)
        {
            return udal.Add(entity);
        }

        public bool Delete(int id)
        {
            LoginInfo entity = new LoginInfo();
            entity.Id = id;
            udal._dbContext.Entry(entity).State = System.Data.Entity.EntityState.Unchanged;
            entity.IsDelete = 1;
            return udal.SaveChanges();
        }

        public IEnumerable<LoginInfo> Getall()
        {
            return udal.GetAll();
        }
    }
}
